package com.hmi.simulatedrive.fragment

import android.os.Bundle
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.hmi.simulatedrive.activity.MainActivity
import com.hmi.simulatedrive.databinding.FragmentSettingBinding
import com.hmi.simulatedrive.utils.Constant.EVENT_WHAT_UPDATE_WEBRTC
import com.hmi.simulatedrive.utils.Constant.SETTING_CONTROLLER_PORT
import com.hmi.simulatedrive.utils.Constant.SETTING_IP
import com.hmi.simulatedrive.utils.Constant.SETTING_LOCATION_PORT
import com.hmi.simulatedrive.utils.Constant.SETTING_SIMULATE_NAVI
import com.hmi.simulatedrive.utils.Constant.SETTING_UNITY_PORT
import com.hmi.simulatedrive.utils.Constant.SETTING_WEBRTC_URL
import org.greenrobot.eventbus.EventBus

class SettingFragment: BaseFragment() {
    private lateinit var settingBinding: FragmentSettingBinding
    private lateinit var viewModel: SettingFragmentViewModel
    companion object {
        val instance: SettingFragment by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            SettingFragment()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProvider(this)[SettingFragmentViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        settingBinding = FragmentSettingBinding.inflate(inflater)
        initView()
        return settingBinding.root
    }

    /**
     * 初始化界面内容
     * */
    private fun initView() {
        viewModel.settingLiveData.observe(requireActivity()) {
            settingBinding.edtCenterIp.setText(it.commonUrl)
            settingBinding.edtCenterPort.setText(it.locationPort)
            settingBinding.edtControllerPort.setText(it.controllerPort)
            settingBinding.edtUnityPort.setText(it.unityPort)
            settingBinding.edtWebrtcUrl.setText(it.webrtcUrl)
            settingBinding.swtichSimulateNavi.isChecked = it.isSimulateNav
        }

        settingBinding.tvSettingOk.setOnClickListener(View.OnClickListener { // 用户点击确定
            // 检查IP和端口号是不是符合规定
            val ipStr: String = settingBinding.edtCenterIp.getText().toString().trim { it <= ' ' }
            if (!RegexUtils.isIP(ipStr)) {
                ToastUtils.showShort("IP 地址不符合规范，请检查！")
                return@OnClickListener
            }
            val locationPortStr: String = settingBinding.edtCenterPort.getText().toString().trim { it <= ' ' }
            val controllerPortStr: String = settingBinding.edtControllerPort.getText().toString().trim { it <= ' ' }
            val unityPortStr: String = settingBinding.edtUnityPort.getText().toString().trim { it <= ' ' }
            val webRTCUrlStr = "http://" + settingBinding.edtWebrtcUrl.getText().toString().trim { it <= ' ' }
            val isSimulate: Boolean = settingBinding.swtichSimulateNavi.isChecked()
            SPUtils.getInstance().put(SETTING_IP, ipStr, true)
            SPUtils.getInstance().put(SETTING_LOCATION_PORT, locationPortStr, true)
            SPUtils.getInstance().put(SETTING_CONTROLLER_PORT, controllerPortStr, true)
            SPUtils.getInstance().put(SETTING_UNITY_PORT, unityPortStr, true)
            SPUtils.getInstance().put(SETTING_WEBRTC_URL, webRTCUrlStr, true)
            SPUtils.getInstance().put(SETTING_SIMULATE_NAVI, isSimulate)
            // 更新ViewModel中的值
            val newSettingModel = SettingModel(ipStr, locationPortStr, controllerPortStr, unityPortStr, webRTCUrlStr, isSimulate)
            viewModel.updateSettingModel(newSettingModel)
            viewModel.settingLiveData.postValue(newSettingModel)
            parentFragmentManager.popBackStack()

            // 重新连接服务器
            (requireActivity() as MainActivity).initJeroMQ()
            val webRTCMsg = Message.obtain()
            webRTCMsg.what = EVENT_WHAT_UPDATE_WEBRTC
            EventBus.getDefault().post(webRTCMsg)
        })

        settingBinding.tvSettingCancel.setOnClickListener { parentFragmentManager.popBackStack() }
    }
}